package com.wk.warehouse.controller;

import java.util.List;

import com.wk.warehouse.entity.InStore;
import com.wk.warehouse.entity.Purchase;
import com.wk.warehouse.entity.Result;
import com.wk.warehouse.service.PurchaseService;
import com.wk.warehouse.service.StoreService;
import com.wk.warehouse.page.Page;
import com.wk.warehouse.util.CurrentUser;
import com.wk.warehouse.util.TokenUtils;
import com.wk.warehouse.util.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;


@RestController
@RequestMapping("/purchase")
public class PurchaseController {

	@Autowired
	private PurchaseService purchaseService;
	@Autowired
	private StoreService storeService;

	/**
	 * 所有仓库
	 */
	@GetMapping("/store-list")
	public Result storeList() {
		return Result.ok(storeService.storeList());
	}

	/**
	 * 分页模糊查询所有采购单
	 */
	@GetMapping("/purchase-page-list")
	public Result purchasePageList(Purchase purchase, Page page) {
		// 获取总条数
		int totalNum = purchaseService.selectCount(purchase);
		page.setTotalNum(totalNum);

		// 查询采购单
		List<Purchase> purchaseList = purchaseService.purchasePageQuery(purchase, page);
		page.setResultList(purchaseList);
		return Result.ok(page);
	}

	/**
	 * 导出数据
	 */
	@GetMapping("/exportTable")
	public Result exportTable(Purchase purchase, Page page){
		page = new Page(9999, 1); // 导出模糊查询所有数据
		// 要导出的数据
		List<Purchase> purchaseList = purchaseService.purchasePageQuery(purchase, page);
		return Result.ok(purchaseList);
	}

	/**
	 * 添加采购单
	 */
	@PostMapping("/purchase-add")
	public Result addPurchase(@RequestBody Purchase purchase){
		purchaseService.addPurchase(purchase);
		return Result.ok("添加采购单成功！");
	}

	/**
	 * 修改采购单
	 */
	@PutMapping("/purchase-update")
	public Result updatePurchase(@RequestBody Purchase purchase){
		purchaseService.updatePurchase(purchase);
		return Result.ok("采购单修改成功！");
	}

	/**
	 * 删除采购单
	 */
	@DeleteMapping("/purchase-delete/{buyId}")
	public Result deletePurchase(@PathVariable int buyId){
		purchaseService.deletePurchase(buyId);
		return Result.ok("删除采购单成功！");
	}

	/**
	 * 生成入库单
	 */
	@PostMapping("/in-warehouse-record-add")
	public Result addInWarehouseRecord(@RequestBody Purchase purchase, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String clientToken){
		InStore inStore = new InStore();
		inStore.setStoreId(purchase.getStoreId());
		inStore.setProductId(purchase.getProductId());
		inStore.setInNum(purchase.getFactBuyNum());
		// 获取创建人id
		CurrentUser currentUser = TokenUtils.getCurrentUser(clientToken);
		int createBy = currentUser.getUserId();
		inStore.setCreateBy(createBy);

		purchaseService.addInWarehouseRecord(inStore, purchase.getBuyId());
		return Result.ok("生成入库单成功！");
	}
}
